//
//  MainToast.swift
//  MM2
//
//  Created by 李成明 on 2022/1/4.
//

import Foundation
import UIKit
import Kingfisher

class MainToast: MViewController {
    
    static let share = MainToast()

    override func viewDidLoad() {
        view.addsubViews([toastLabel, imageView])
    }
    
    private let window: UIWindow = UIWindow.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
    
    private lazy var imageView: UIImageView = {
        let view = UIImageView(frame: CGRect(x: kScreenWidth/2 - 50, y: kScreenHeight/2 - 50, width: 50, height: 50))
        let path = Bundle.main.path(forResource:"loading", ofType:"gif")
        let url = URL(fileURLWithPath: path!)
        let provider = LocalFileImageDataProvider(fileURL: url)
        imageView.kf.setImage(with: provider)
        return view
    }()
    
    private lazy var toastLabel: UILabel = {
        let view = UILabel()
        view.backgroundColor = .black
        view.font = .systemFont(ofSize: 16)
        view.numberOfLines = 0
        view.textAlignment = .center
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 8
        return view
    }()
    
    private func beginShow() {
        self.window.rootViewController = self
        self.window.alpha = 1
        self.window.isHidden = false
    }
    
    func endShow() {
        self.window.rootViewController = nil
        self.window.alpha = 0
        self.window.isHidden = true
        imageView.isHidden = true
        toastLabel.isHidden = true
    }
    
    func showLoading(delay: Float = 1, autoDismiss: Bool = true) {
        beginShow()
        imageView.isHidden = false
        if autoDismiss {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
                self.endShow()
            })
        }
    }
    
    func showToast(delay: Float = 0.5, autoDismiss: Bool = true, text: String = "出错啦!") {
        beginShow()
        toastLabel.isHidden = false
        toastLabel.text = text
        
        let size = toastLabel.sizeThatFits(CGSize(width: 150, height: CGFloat.greatestFiniteMagnitude))
        toastLabel.frame = CGRect(x: (kScreenWidth - size.width)/2, y: (kScreenHeight - size.height)/2, width: size.width, height: size.height)
        
        if autoDismiss {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
                self.endShow()
            })
        }
    }
    
}
